const router = require("koa-router")();
const hwconfig = require("../consts/hwapi");

router.prefix("/api/hwcloud");

/** 华为token信息。 */
const hwToken = new Map();

/**
 * 获取token。
 */
let getToken = function (ecs) {
  return new Promise((resolve, reject) => {
    let currentToken = hwToken.get(ecs.projectId);

    if (!currentToken || currentToken.token == null || currentToken.expiresAt.getTime() - new Date().getTime() <= 0) {
      ctx.httpClient.post(`https://${ecs.identityUrl}/v3/auth/tokens`, JSON.stringify(hwconfig.getAuth(ecs.projectId))).then(
        res => {
          let json = JSON.parse(res.body);

          let token = {
            token: res.headers["x-subject-token"],
            expiresAt: json.token ? new Date(json.token.expires_at) : new Date()
          }

          console.log(token);

          hwToken.set(ecs.projectId, token);

          resolve(token);
        },
        reason => {
          console.log(reason);

          reject(reason);
        }
      ).catch(err => {
        reject(err);
      });
    } else {
      resolve(currentToken);
    }
  });
};

/**
 * 获取华为云服务接口认证token。
 */
router.get("/token", async (ctx, next) => {
  await ctx.httpClient.post(`https://${hwconfig.url.identity}/v3/auth/tokens`, JSON.stringify(hwconfig.auth)).then(
    res => (ctx.body = {
      token: res.headers["x-subject-token"]
    }),
    reason => (ctx.body = {
      msg: reason
    })
  );
});

/**
 * 获取华为云弹性服务器列表
 */
router.get("/servers", async (ctx, next) => {
  await (ctx.body = {
    servers: hwconfig.getAllServers(),
    metrics: hwconfig.metrics
  });
});

/**
 *  获取华为弹性云主机状态。
 */
router.get("/ecs/status/:ecsId", async (ctx, next) => {
  let ecs = hwconfig.getServerDetail(ctx.params.ecsId);

  await getToken(ecs);

  await ctx.httpClient.get(`https://${ecs.regionUrl}/v2.1/${ecs.projectId}/servers`, {
    headers: {
      "x-auth-token": hwToken.get(ecs.projectId).token
    }
  }).then(
    res => (ctx.body = res.body),
    error => (ctx.body = {
      msg: error
    })
  );
});

/**
 * 获取弹性云服务配置信息。
 */
router.get("/ecs/:ecsId/detail/:flavorsId", async (ctx, next) => {
  let ecs = hwconfig.getServerDetail(ctx.params.ecsId);

  await getToken(ecs);

  await ctx.httpClient.get(`https://${ecs.regionUrl}/v2/${ecs.projectId}/flavors/${ctx.params.flavorsId}`, {
    headers: {
      "x-auth-token": hwToken.get(ecs.projectId).token
    }
  }).then(
    res => (ctx.body = res.body),
    reason => (ctx.body = {
      msg: reason
    })
  );
});

/**
 *  获取华为弹性云主机硬件监控信息。
 */
router.post("/ecs/info/:ecsId", async (ctx, next) => {
  let from = Math.round(new Date(ctx.request.body.from).getTime());
  let to = Math.round(new Date(ctx.request.body.to).getTime());

  let ecs = hwconfig.getServerDetail(ctx.params.ecsId);

  await getToken(ecs);

  let url = `https://${ecs.regionUrl}/V1.0/${ecs.projectId}/metric-data?filter=${ctx.request.body.filter || "average"}&period=${ctx.request.body.period || 300}&to=${to}&from=${from}&dim.0=instance_id,${ctx.params.ecsId}&metric_name=${ctx.request.body.metricName}&namespace=SYS.ECS`;

  await ctx.httpClient.get(url, {
    headers: {
      "x-auth-token": hwToken.get(ecs.projectId).token
    }
  }).then(
    res => (ctx.body = res.body),
    reason => (ctx.body = {
      msg: reason
    })
  );
});

module.exports = router;